package com.example.oauth2.config;

import com.example.oauth2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyonghui
 * @description: 授权服务器
 * @date 2021/12/5 13:43
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    //    @Autowired
//    @Qualifier("redisTokenStore")
//    private TokenStore redisTokenStore;

    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore jwtTokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * @description: 使用密码模式所需配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //配置JWT内容增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        tokenEnhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManager).userDetailsService(userService)
//                .tokenStore(redisTokenStore);
                //配置存储令牌策略
                .tokenStore(jwtTokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(tokenEnhancerChain);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client-id
                .withClient("admin")
                //配置client-secret
                .secret(passwordEncoder.encode("123"))
                //配置访问token的有效期
//                .accessTokenValiditySeconds(3600)
                //配置申请的权限范围
                //配置grant_type，表示授权类型（authorization_code：令牌模式）
//                .scopes("all")
//                .autoApprove(true) //自动授权
//                .accessTokenValiditySeconds(3600) //配置访问token的有效期
//                .refreshTokenValiditySeconds(864000) //配置刷新令牌的有效期
//                .redirectUris("https://www.baidu.com") // //配置redirect-url,用于授权成功后跳转
//                .authorizedGrantTypes("authorization_code", "refresh_token");
                //授权类型-使用密码模式
                .scopes("all")
                .accessTokenValiditySeconds(3600) //配置访问token的有效期
                .refreshTokenValiditySeconds(864000) //配置刷新令牌的有效期
                // 允许密码授权和刷新令牌授权（通过refresh_token刷新access_token | 使用刷新令牌来获取新的访问令牌）
                .authorizedGrantTypes("password", "refresh_token");
                // 静默授权
//                .scopes("read")
//                .accessTokenValiditySeconds(3600) //配置访问token的有效期
//                .redirectUris("https://www.baidu.com") // //配置redirect-url,用于授权成功后跳转
//                .authorizedGrantTypes("implicit");
                // 客户端授权 - 客户端凭证授权模式不会发行refresh_token
//                .scopes("read")
//                .accessTokenValiditySeconds(3600) //配置访问token的有效期
//                .authorizedGrantTypes("client_credentials");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //获取密钥需要身份认证,使用单点登录时必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }
}
